package com.luojiaoj.user

import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import com.luojiaoj.update.Photo
import com.luojiaoj.User

class UploadService {

    def grailsApplication

    def savePhoto(InputStream stream, String orgFileName) {
        String suffix  = orgFileName.substring(orgFileName.lastIndexOf(".") + 1)
        String filename = System.currentTimeMillis() + "-" + (int)(100 * Math.random())
        BufferedImage image = ImageIO.read(stream)

        File uploadDir = new File(grailsApplication.config.ljoj.upload.dir)
        File imageFolder = new File(uploadDir, 'image')
        if (!imageFolder.exists()){
            imageFolder.mkdirs()
        }
        File imageFile = new File(imageFolder, filename + '.' + suffix)

        OutputStream out = null

        try {
            out = new FileOutputStream(imageFile)
            ImageIO.write(image, suffix, out);
        } catch (IOException e) {
            e.printStackTrace()
        } catch (Exception e) {
            e.printStackTrace()
        } finally {
            out.close()
        }

    }

    def saveAsUserAvatar(InputStream stream, String orgFileName, long userId) {
        String suffix  = orgFileName.substring(orgFileName.lastIndexOf(".") + 1)
        String filename = System.currentTimeMillis() + "-" + (int)(100 * Math.random())
        BufferedImage image = ImageIO.read(stream)

        File uploadDir = new File(grailsApplication.config.ljoj.upload.dir)
        File imageFolder = new File(uploadDir, 'image')
        if (!imageFolder.exists()){
            imageFolder.mkdirs()
        }
        File imageFile = new File(imageFolder, filename + '.' + suffix)

        OutputStream out = null

        try {
            out = new FileOutputStream(imageFile)
            ImageIO.write(image, suffix, out);
        } catch (IOException e) {
            e.printStackTrace()
        } catch (Exception e) {
            e.printStackTrace()
        } finally {
            out.close()
        }

        Photo photo = new Photo(fileName: filename, suffix: suffix).save(failOnError: true)
        User curUser = User.get(userId)
        curUser.avatar = photo
        curUser.save(failOnError: true)
    }
}
